import plugin from '../../../lib/plugins/plugin.js'
import co from '../../../lib/common/common.js'
import { exec , execSync } from 'child_process'
import fs from 'fs'
import fetch from 'node-fetch'
import { Config } from '../components/index.js'
import { common } from '../model/index.js'
let sendFile = {}
const path = process.cwd() + '/plugins/example/'
export class XyInstall extends plugin {
  constructor () {
    super({
      /** 功能名称 */
      name: '小月安装插件',
      /** 功能描述 */
      dsc: '安装插件',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 500,
      rule: [
        {
          reg: '^#?(小月)?安装插件包(列表)?',
          fnc: 'installPlugin',
        },
        {
          reg: '^#?(小月)?安装插件(列表)?',
          fnc: 'installCj',
        },
        {
          reg: '^#?(小月)?更新全部依赖$',
          fnc: 'installModel',
        }
      ]
    })
  }

  async accept(e) {
    if (!e.isMaster) return false
    if (!sendFile[e.user_id] || !e.file) return
    if (e.isGroup) return e.reply('只支持私聊安装')
    let fileUrl = await e.friend.getFileUrl(e.file.fid);
		let filename = path + e.file.name
    e.reply('正在安装插件中...请耐心等候')
    let res = await co.downFile(fileUrl,filename)
    if (res) {
    e.reply('安装插件成功，可发[#查询插件]进行查看')
    } else {
    e.reply('安装插件失败')
    }
    clearTimeout(sendFile[e.user_id])
    delete sendFile[e.user_id]
  }
  async installPlugin(e){
    if (!e.isMaster) return false
    let config = await Config.xyaz
    if (e.msg.includes('列表')) {
      let msg = ['插件均来自于插件库\nhttps://gitee.com/yhArcadia/Yunzai-Bot-plugins-index\n指令：[安装插件包(序列号)]可快速安装']
      config = config.plugins
      for (let i = 0; i < config.length; i++) {
      msg.push(`${i+1}.` + config[i].name)
      }
      common.getforwardMsg(e,msg,'查看自定义插件包安装列表',0,false,true)
      return true
    }
    let url = e.msg.replace(/#|安装插件包|小月/g, '').trim()
    let num = e.msg.match(/\d+/)?.[0]
    let name = url.split('/')[4]
    if (num && (Number(num) > (config.plugins).length || Number(num) < 1)) return e.reply('请输入正确的序列号')
    if (num) {
      num = Number(num) - 1
      config = config.plugins
      url = config[num].url
      name = config[num].name
    } 
    else {
    if (!url.includes('gitee') && !url.includes('github')) return e.reply('格式错误，示范：\n#安装插件包https://gitee.com/yunxiyuan/xiaoyue-plugin')
    }
    e.reply('正在安装插件包中...请耐心等候')
    await common.sleep(1000)
    let cmd = ` git clone --depth=1 ${url}${url.includes('.git') ? '' : '.git'} ./plugins/${name} `
    let ret = await common.execSync(cmd)
    if (ret.error) {
      await e.reply('安装失败\n' + ret.error)
      return
    }
    e.reply(`安装插件包${name}成功`)
    if (fs.existsSync(`./plugins/${name}/package.json`)) {
    e.reply('检测到package.json，开始安装依赖...请耐心等候')
        await common.sleep(1000)
        let pi = `pnpm i -P --prefix ./plugins/${name}/`
        let pcmd = await common.execSync(pi)
    if (pcmd.error) {
        return e.reply('安装失败\n' + ret.error)
        } 
        else {
        return e.reply('安装完成')
        }
  } 
        else {
        e.reply('插件安装完成')
        }
        let xyset = await Config.xyss
        let therestart = xyset.restart
        if (therestart) {
        setTimeout(() => new Restart(this.e).restart(), 600)
        } 
        else {
        e.reply('请自行重启bot')
        }
  }

  async installCj(e) {
    if (!e.isMaster) return false
    let url = e.msg.replace(/#|安装插件|小月/g, '').trim()
    if (url.includes('gitee') || url.includes('github')) {
       if (!url.includes('raw')) return e.reply('格式错误，示范：\n#安装插件https://gitee.com/Saury-loser/Saury/raw/master/谁艾特我.js')
       url = decodeURI(url)
       try {
       let res = await fetch(url)
       let js = await res.text()
       let jsName = url.split('/')[7]
       fs.writeFileSync(`./plugins/example/${jsName}`,js,'utf-8')
       e.reply('安装插件成功')
       } catch (err) {
        logger.warn(err)
        e.reply('安装插件失败\n'+ err.toString())
       }
       return true
    }
    let config = await Config.xyaz
    if (e.msg.includes('列表')) {
      let msg = ['插件均来自于插件库\nhttps://gitee.com/yhArcadia/Yunzai-Bot-plugins-index\n指令：[安装插件(序列号)]可快速安装']
      config = config.js
      for (let i = 0; i < config.length; i++) {
      msg.push(`${i+1}.` + config[i].name)
      }
      common.getforwardMsg(e,msg,'查看自定义插件安装列表',0,false,true)
      return true
    }
    let num = e.msg.match(/\d+/)?.[0]
    if (num && (Number(num) > (config.js).length || Number(num) < 1)) return e.reply('请输入正确的序列号')
    if (num) {
      num = Number(num) - 1
      config = config.js
      url = config[num].url
      try {
      let res = await fetch(url)
      let js = await res.text()
      let jsName = url.split('/')[7]
      fs.writeFileSync(`./plugins/example/${jsName}`,js,'utf-8')
      e.reply('安装插件成功')
    let xyset = await Config.xyss
    let therestart = xyset.restart
    if (therestart) {
    setTimeout(() => new Restart(this.e).restart(), 600)
    } else {
    e.reply('请自行重启bot')
    }
      } catch (err) {
        logger.warn(err)
        e.reply('安装插件失败\n'+ err.toString())
       }
       return true
    }

    if (sendFile[e.user_id]) return e.reply('请发送插件进行安装')
    if (e.isGroup) return e.reply('请私聊使用')
    sendFile[e.user_id] = true
    sendFile[e.user_id] = setTimeout(() => {
       if (sendFile[e.user_id]) {
        delete sendFile[e.user_id]
        e.reply('已超时，安装结束')
       }
    },30 * 1000)
    e.reply('请30秒内发送插件进行安装')
  }
  
  async installModel(e){
   if (!e.isMaster) return false
   let xyset = await Config.xyss
   let therestart = xyset.restart
   e.reply('正在更新全部依赖...')
   let model = `pnpm up`
   let modcmd = await common.execSync(model)
    if (modcmd.error) {
        return e.reply('更新失败\n' + modcmd.error)
        } else {
          if (therestart) {
          setTimeout(() => new Restart(this.e).restart(), 600)
          } else {
          return e.reply('更新完成，请自行重启Bot')
          }
       }
  }
  
}